<template>
  <el-scrollbar>
    <div class="container">
      <div
        class="bg"
        :style="{ backgroundImage: `url(${baseUrl + playInfo.image})` }"
      ></div>
      <div
        class="mask"
        :style="
          playInfo.image
            ? { backgroundColor: 'rgba(0,0,0,.5)' }
            : { backgroundColor: '#292a2b' }
        "
      ></div>
      <div class="content">
        <div class="top">
          <div class="top_left">
            <div class="operate">
              <div class="btn" v-show="songsId" @click="collectSongsList">
                <i
                  :style="isCollect ? 'color:#F06868' : ''"
                  :class="[
                    'iconfont',
                    isCollect ? 'icon-jushoucanggift' : 'icon-jushoucang',
                  ]"
                ></i>
                <span>收藏</span>
              </div>
              <el-dropdown trigger="click" @visible-change="visiChange">
                <div class="btn">
                  <i style="font-size: 14px" class="iconfont icon-jiahao"></i>
                  <span>添加</span>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      @click="visiCommand(item)"
                      v-for="(item, index) in mySongs"
                      :key="index"
                      >{{ item.title }} 5</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
<!-- 
              <div class="btn" @click="download">
                <i style="font-size: 17px" class="iconfont icon-xiazai"></i>
                <span>下载</span>
              </div> -->
              <div class="btn" @click="delSomeSongs">
                <i style="font-size: 17px" class="iconfont icon-shanchu"></i>
                <span>删除</span>
              </div>
            </div>
            <div class="music_table">
              <el-table
                height="100%"
                ref="tableRef"
                :data="songList"
                @selection-change="handleSelectionChange"
                @cell-mouse-enter="cellHover"
                @cell-mouse-leave="cellLeave"
              >
                <el-table-column type="selection" width="50" />
                <el-table-column type="index" width="20">
                  <template #default="scope">
                    <el-image
                      v-if="playInfo.id == scope.row.id && playInfo.isPlay"
                      :src="play"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="歌曲" width="700">
                  <template #default="scope">
                    <div class="name">
                      <div class="song_info">
                        <span
                          :class="[
                            'hover',
                            playInfo.id == scope.row.id && playInfo.isPlay
                              ? 'is_white'
                              : '',
                          ]"
                          >{{ scope.row.title + "-" + scope.row.id }}</span
                        >
                      </div>
                      <div class="btns" v-show="scope.row.hover">
                        <i
                          @click="selPlay(scope.row, scope.$index)"
                          :class="[
                            'iconfont',
                            playInfo.id == scope.row.id && playInfo.isPlay
                              ? 'icon-zanting1'
                              : 'icon-bofang',
                          ]"
                        ></i>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="歌手" width="250">
                  <template #default="scope">
                    <span
                      :class="[
                        'hover',
                        playInfo.id == scope.row.id && playInfo.isPlay
                          ? 'is_white'
                          : '',
                      ]"
                      >{{ scope.row.user?.nickname }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column label="时长">
                  <template #default="scope">
                    <i
                      @click="delSongs(scope.$index)"
                      v-show="scope.row.hover"
                      class="iconfont icon-shanchu"
                    ></i>
                    <span v-show="!scope.row.hover">{{
                      timeFilter(scope.row.duration)
                    }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <el-scrollbar>
            <div class="top_right">
              <div class="cover">
                <el-image :src="baseUrl + playInfo.image" />
              </div>
              <div class="info">
                <span>歌曲名：{{ playInfo.title }}</span>
                <span>歌手：{{ playInfo.user?.nickname }}</span>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="bottom">
          <div class="control">
            <i @click="prevSong" class="iconfont icon-shangyishou"></i>
            <i
              @click="controlPlay"
              style="margin: 0 40px"
              :class="[
                'iconfont',
                playInfo.isPlay ? 'icon-zanting' : 'icon-bofang1',
              ]"
            ></i>
            <i @click="nextSong" class="iconfont icon-xiayishou"></i>
          </div>
          <div class="schedule">
            <div class="info">
              <span>
                {{ playInfo.title + " - " + playInfo.user?.nickname }}
              </span>
              <span>{{
                timeFilter(playInfo.isTime) +
                " / " +
                timeFilter(playAudio?.duration)
              }}</span>
            </div>
            <el-slider
              :show-tooltip="false"
              :min="0"
              :max="playAudio?.duration"
              v-model="playInfo.isTime"
              @input="sliderInput"
              @change="sliderChange"
            />
          </div>
          <div class="other">
            <div class="order" @click="changeOrder">
              <i v-show="order == 1" class="iconfont icon-shunxubofang"></i>
              <i v-show="order == 2" class="iconfont icon-xunhuanbofang"></i>
              <i v-show="order == 3" class="iconfont icon-danquxunhuan"></i>
              <i v-show="order == 4" class="iconfont icon-suijibofang"></i>
            </div>
            <i
              @click="changeColllect"
              :style="playInfo.isCollect ? 'color:#F06868' : ''"
              :class="[
                'iconfont',
                playInfo.isCollect ? 'icon-jushoucanggift' : 'icon-jushoucang',
              ]"
            ></i>
            <i class="iconfont icon-xiazai"></i>
            <div class="volume">
              <i
                @click="mute"
                :class="[
                  'iconfont',
                  volume == 0 ? 'icon-jingyin' : 'icon-yinliang2',
                ]"
              ></i>
              <el-slider
                @input="volumeInput"
                :show-tooltip="false"
                v-model="volume"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <audio
      ref="playAudio"
      style="display: none"
      :src="baseUrl + playInfo.audio"
    ></audio>
  </el-scrollbar>
</template>

<script setup>
import play from "@/assets/gif/play.gif";
import { onMounted, ref, computed } from "vue";
import { PersistentStore } from "@/stores";
import { ElMessage } from "element-plus";
import {
  musicCollectIsCollect,
  musicCollectDel,
  musicCollectAdd,
  songsCollectAdd,
  songsCollectDel,
  songsCollectIsCollect,
  songsMy,
  songsListAdd,
  musicDownload,
} from "@/http/api";
const baseUrl = import.meta.env.VITE_API_URL;
const playAudio = ref();
const persistentStore = PersistentStore();
const playCurrent = computed(() => persistentStore.songListInfo.index);
const songList = computed(() => persistentStore.songListInfo.list);
const songsId = computed(() => persistentStore.songListInfo.id);
const playInfo = ref({});
const isCollect = ref(false);
const tableRef = ref();
const volume = ref(0);
const order = ref(1);
const isInput = ref(false);
const mySongs = ref([]);

onMounted(() => {
  volume.value = playAudio.value.volume * 100;
  playInfo.value = deepClone(songList.value[playCurrent.value]);
  playAudio.value.addEventListener("timeupdate", playUpdate);
  playAudio.value.addEventListener("ended", ended);
  getSongsListCollect();
  musicIsCollect();
  // window.addEventListener("keydown", (e) => {
  //   if (e.code == "Space") {
  //     playInfo.value.isPlay = !playInfo.value.isPlay;
  //     palyMusic();
  //   }
  // });
  window.addEventListener(
    "message",
    (e) => {
      const info = JSON.parse(e.data);
      persistentStore.setSongListInfo(info);
      playInfo.value = deepClone(songList.value[playCurrent.value]);
      playInfo.value.isPlay = true;
      playAudio.value.currentTime = 0;
      palyMusic();
      getSongsListCollect();
      musicIsCollect();
    },
    false
  );
});

const getSongsListCollect = async () => {
  const { data } = await songsCollectIsCollect({
    songs_id: songsId.value,
  });
  isCollect.value = data.is_collect;
};

const collectSongsList = async () => {
  if (isCollect.value) {
    const { code, data } = await songsCollectDel({
      songs_id: songsId.value,
    });
    if (code == 200) {
      isCollect.value = false;
    }
  } else {
    const { code, data } = await songsCollectAdd({
      songs_id: songsId.value,
    });
    if (code == 200) {
      isCollect.value = true;
    }
  }
};

const deepClone = (e) => {
  return JSON.parse(JSON.stringify(e));
};

const musicIsCollect = async () => {
  const { data } = await musicCollectIsCollect({
    music_id: playInfo.value.id,
  });
  playInfo.value.isCollect = data.is_collect;
};

const changeColllect = async () => {
  if (playInfo.value.isCollect) {
    const { code, data } = await musicCollectDel({
      music_id: playInfo.value.id,
    });
    if (code == 200) {
      playInfo.value.isCollect = !playInfo.value.isCollect;
    }
  } else {
    const { code, data } = await musicCollectAdd({
      music_id: playInfo.value.id,
    });
    if (code == 200) {
      playInfo.value.isCollect = !playInfo.value.isCollect;
    }
  }
};

const visiChange = async (e) => {
  if (e) {
    const { data } = await songsMy();
    mySongs.value = data.songs;
  }
};

const visiCommand = async (e) => {
  const arr = tableRef.value.getSelectionRows().map((el) => el.id);
  if (arr.length) {
    const { code, data } = await songsListAdd({
      songs_id: e.id,
      music_id: arr.join(","),
    });
    if (code == 200) {
      ElMessage.success("添加成功");
      tableRef.value.clearSelection();
    }
  } else {
    ElMessage.error("请选择歌曲");
  }
};

const changeOrder = () => {
  if (order.value == 4) {
    order.value = 1;
    return;
  }
  order.value++;
};

const mute = () => {
  if (volume.value == 0) {
    volume.value = 50;
    playAudio.value.volume = 0.5;
  } else {
    volume.value = 0;
    playAudio.value.volume = 0;
  }
};

const timeFilter = (e) => {
  let timeFormat = "00:00";
  e = parseInt(e);
  if (e) {
    let minutes = Math.floor(e / 60);
    let second = e % 60;
    timeFormat =
      minutes.toString().padStart(2, "0") +
      ":" +
      second.toString().padStart(2, "0");
  }
  return timeFormat;
};

const handleSelectionChange = (e) => {
  console.log(e);
};

const delSongs = (e) => {
  songList.value.splice(e, 1);
};

const delSomeSongs = () => {
  const arr = tableRef.value.getSelectionRows().map((el) => el.id);
  persistentStore.songListInfo.list = songList.value.filter(
    (item) => !arr.includes(item.id)
  );
};

// const download = async () => {
//   const arr = tableRef.value.getSelectionRows().map((el) => el.id);
//   console.log(arr);
//   if (!arr.length) return;
//   const { data } = await musicDownload({
//     id: arr.join(","),
//   });
//   const musicList = data.music;
//   for (let index = 0; index < musicList.length; index++) {
//     const path = baseUrl + musicList[index].audio;
//   }
// };

const selPlay = (e, i) => {
  persistentStore.editIndex(i);
  if (e.id != playInfo.value.id) {
    playAudio.value.currentTime = 0;
    playInfo.value = {
      isPlay: true,
      ...e,
    };
  } else {
    playInfo.value.isPlay = !playInfo.value.isPlay;
  }
  palyMusic();
  musicIsCollect();
};

const controlPlay = () => {
  playInfo.value.isPlay = !playInfo.value.isPlay;
  palyMusic();
};

const palyMusic = () => {
  playInfo.value.isPlay ? playAudio.value.play() : playAudio.value.pause();
};

const playUpdate = () => {
  if (!isInput.value) playInfo.value.isTime = playAudio.value.currentTime;
};

const prevSong = () => {
  playAudio.value.currentTime = 0;
  if (order.value == 1 || order.value == 2) {
    if (playCurrent.value != 0) {
      persistentStore.editIndex(playCurrent.value - 1);
    }
  } else if (order.value == 4) {
    const number = Math.floor(Math.random() * (songList.value.length - 1));
    if (number != playCurrent.value) {
      persistentStore.editIndex(number);
      return;
    }
    prevSong();
  }
  playInfo.value = {
    isPlay: true,
    ...songList.value[playCurrent.value],
  };
  playAudio.value.play();
  musicIsCollect();
};
const nextSong = () => {
  playAudio.value.currentTime = 0;
  if (order.value == 1) {
    if (playCurrent.value + 1 < songList.value.length) {
      persistentStore.editIndex(playCurrent.value + 1);
    }
  } else if (order.value == 2) {
    if (playCurrent.value == songList.value.length - 1) {
      persistentStore.editIndex(0);
    } else {
      persistentStore.editIndex(playCurrent.value + 1);
    }
  } else if (order.value == 4) {
    const number = Math.floor(Math.random() * (songList.value.length - 1));
    if (number != playCurrent.value) {
      persistentStore.editIndex(number);
      return;
    }
    prevSong();
  }
  playInfo.value = {
    isPlay: true,
    ...songList.value[playCurrent.value],
  };
  playAudio.value.play();
  musicIsCollect();
};

const ended = () => {
  playAudio.value.currentTime = 0;
  if (order.value == 1) {
    if (songList.value.length > playCurrent.value + 1) {
      persistentStore.editIndex(playCurrent.value + 1);
    } else {
      playInfo.value.isPlay = false;
    }
  } else if (order.value == 2) {
    if (songList.value.length > playCurrent.value + 1) {
      persistentStore.editIndex(playCurrent.value + 1);
    } else {
      persistentStore.editIndex(0);
    }
  } else if (order.value == 4) {
    const number = Math.floor(Math.random() * (songList.value.length - 1));
    if (number != playCurrent.value) {
      persistentStore.editIndex(number);
      return;
    }
    ended();
  }
  playInfo.value = {
    isPlay: true,
    ...songList.value[playCurrent.value],
  };
  playAudio.value.play();
  musicIsCollect();
};

const sliderInput = (e) => {
  isInput.value = true;
};

const sliderChange = (e) => {
  isInput.value = false;
  playAudio.value.currentTime = parseFloat(e);
};

const volumeInput = (e) => {
  playAudio.value.volume = e / 100;
};

const cellHover = (e) => {
  e.hover = true;
};
const cellLeave = (e) => {
  e.hover = false;
};
</script>

<style lang="scss" scoped>
@import "index.scss";
</style>
